<template>
  <div class="data-visualization">
    <!-- 标题 + 区域选择 水平布局 -->
    <div class="header">
      <h2 class="page-title">电力数据可视化</h2>
      <el-row :gutter="20" class="select-container">
        <el-col :span="10">
          <div class="custom-select-container">
            <el-select
                v-model="selectedRegion"
                placeholder="请选择区域"
                @change="fetchRegionData"
                style="width: 100%;"
                v-loading="regionLoading"
                :disabled="regionList.length === 0"
                popper-class="custom-select-popup"
                clearable
            >
              <el-option
                  v-for="(region, index) in regionList"
                  :key="index"
                  :label="region.label"
                  :value="region.label"
              />
              <template v-if="regionList.length === 0">
                <el-option disabled label="暂无区域数据" value="" />
              </template>
            </el-select>
            <div
                v-if="regionList.length === 0 && !regionLoading"
                class="load-fail-tip"
            >
              区域数据加载失败，请检查网络或联系管理员
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 指标数据雷达图（高度增加） -->
    <el-row :gutter="20" style="margin-top: 30px;">
      <el-col :span="24">
        <chart-card title="区域电力指标监控" >
          <div class="chart-wrapper">
            <div id="metricRadarChart" style="width: 100%; margin: 0 auto; height: 400px;"></div>
          </div>
        </chart-card>
      </el-col>
    </el-row>

    <!-- 设备状态 + 类型分布 双列布局 -->
    <el-row :gutter="20" style="margin-top: 30px;">
      <el-col :span="12">
        <chart-card v-if="barChartData.datasets[0].data.some(v => v > 0)" title="设备运行状态统计">
          <div class="chart-wrapper">
            <bar-chart ref="barChart" :data="barChartData" />
          </div>
        </chart-card>
      </el-col>
      <el-col :span="12">
        <chart-card v-if="pieChartData.datasets[0].data.some(v => v > 0)" title="设备类型分布">
          <div class="chart-wrapper">
            <pie-chart ref="pieChart" :data="pieChartData" />
          </div>
        </chart-card>
      </el-col>
    </el-row>

    <!-- 加载动画 -->
    <el-loading v-if="loading" text="加载中..."></el-loading>
  </div>
</template>

<script>
import ChartCard from '@/components/charts/ChartCard.vue';
import BarChart from '@/components/charts/BarChart.vue';
import PieChart from '@/components/charts/PieChart.vue';
import { getRegionList, getRegionMetrics } from '@/api/region';
import { api } from '@/api';
import {
  Row,
  Col,
  Select,
  Option,
  Loading, Message
} from 'element-ui';
import * as echarts from 'echarts';

export default {
  name: 'DataVisualization',
  components: {
    ChartCard,
    BarChart,
    PieChart,
    ElRow: Row,
    ElCol: Col,
    ElSelect: Select,
    ElOption: Option,
    ElLoading: Loading
  },
  data() {
    return {
      regionLoading: false,
      loading: false,
      selectedRegion: '',
      regionList: [],
      regionMetricData: {},
      metricChart: null,
      barChartData: {
        labels: ['正常设备', '异常设备'],
        datasets: [
          {
            label: '数量',
            data: [0, 0],
            backgroundColor: ['#67C23A', '#F56C6C']
          }
        ]
      },
      pieChartData: {
        labels: ['变压器', '断路器', '继电器', '电容器', '其他设备'],
        datasets: [
          {
            data: [0, 0, 0, 0, 0],
            backgroundColor: ['#409EFF', '#67C23A', '#F56C6C', '#E6A23C', '#909399']
          }
        ]
      },
      refreshTimer: null,
      metricLabels: {
        voltage: '电压 (V)',
        current: '电流 (A)',
        activePower: '有功功率 (kW)',
        reactivePower: '无功功率 (kVar)',
        temperature: '设备温度 (°C)',
        dailyPower: '日用电量 (kWh)',
        monthlyPower: '月用电量 (kWh)',
        totalPower: '累计发电量 (kWh)'
      }
    };
  },
  async mounted() {
    this.$nextTick(async () => {
      this.initMetricChart();
      await this.fetchRegionList();
      if (this.regionList.length > 0) {
        this.selectedRegion = this.regionList[0].label;
        await this.fetchRegionData();
      }
      await this.fetchDeviceStatsData();
      this.refreshTimer = setInterval(async () => {
        if (this.selectedRegion) await this.fetchRegionData();
        await this.fetchDeviceStatsData();
      }, 5000);
    });
  },
  beforeDestroy() {
    clearInterval(this.refreshTimer);
    if (this.metricChart) this.metricChart.dispose();
  },
  methods: {
    // 👇 重点修改：添加雷达图加载动画
    initMetricChart() {
      const radarDom = document.getElementById('metricRadarChart');
      this.metricChart = echarts.init(radarDom);
      const radarOption = {
        tooltip: { trigger: 'item' },
        legend: { top: 10, textStyle: { fontSize: 14 } },
        radar: {
          center: ['50%', '50%'],
          radius: '65%',
          indicator: Object.keys(this.metricLabels).map(key => ({
            name: this.metricLabels[key],
            max: 200
          })),
          splitArea: { show: true, areaStyle: { color: ['rgba(255,255,255,0.3)', 'rgba(200,200,200,0.3)'] } },
          splitLine: { show: true }
        },
        series: [{
          name: '区域指标',
          type: 'radar',
          data: [],
          itemStyle: { color: '#409EFF' },
          areaStyle: { color: 'rgba(64, 158, 255, 0.2)' },
          label: { show: true, color: '#333' },
          // 👇 动画配置：从中心向外生长、渐显
          animationDuration: 1500,    // 动画总时长
          animationEasing: 'cubicOut', // 动画曲线（先慢后快）
          animationDelay: (idx) => idx * 100 // 每个点延迟动画，营造“生长”感
        }]
      };
      this.metricChart.setOption(radarOption);
      // 监听容器大小变化，确保响应式
      const resizeObserver = new ResizeObserver(() => {
        this.metricChart.resize();
      });
      resizeObserver.observe(radarDom);
    },

    updateMetricChart() {
      if (!this.metricChart || Object.keys(this.regionMetricData).length === 0) return;

      const metrics = Object.keys(this.metricLabels);
      const values = metrics.map(key => this.regionMetricData[key] || 0);
      const maxValues = metrics.map((key, index) => {
        const value = values[index];
        switch (key) {
          case 'voltage': return Math.max(value * 1.2, 220);
          case 'current': return Math.max(value * 1.2, 50);
          case 'temperature': return Math.max(value * 1.2, 80);
          case 'dailyPower':
          case 'monthlyPower':
          case 'totalPower': return Math.max(value * 1.2, 1000);
          default: return Math.max(value * 1.2, 100);
        }
      });

      this.metricChart.setOption({
        radar: {
          indicator: metrics.map((key, index) => ({
            name: this.metricLabels[key],
            max: maxValues[index]
          }))
        },
        series: [{
          data: [{
            value: values,
            name: this.selectedRegion || '当前区域'
          }]
        }]
      });
    },

    async fetchRegionList() {
      this.regionLoading = true;
      try {
        const res = await getRegionList();
        this.regionList = res?.data || [];
      } catch (error) {
        console.error('获取区域列表失败:', error);
        Message.error('获取区域列表失败，请稍后再试');
        this.regionList = [];
      } finally {
        this.regionLoading = false;
      }
    },

    async fetchRegionData() {
      if (!this.selectedRegion) {
        Message.warning('请先选择有效区域');
        return;
      }
      this.loading = true;
      try {
        const res = await getRegionMetrics(this.selectedRegion);
        this.regionMetricData = res?.data || {};
        this.updateMetricChart();
      } catch (error) {
        console.error('获取区域电力指标数据失败:', error);
        Message.error('数据加载失败，请稍后再试');
      } finally {
        this.loading = false;
      }
    },

    async fetchDeviceStatsData() {
      this.loading = true;
      try {
        const response = await api.device.list({ page: 1, pageSize: 1000 });
        const devices = response?.data?.records || [];

        const [normalCount, abnormalCount] = devices.reduce((acc, cur) => {
          cur.status === 1 ? acc[0]++ : cur.status === 2 && acc[1]++;
          return acc;
        }, [0, 0]);
        this.barChartData.datasets[0].data = [normalCount, abnormalCount];

        const deviceTypeCounts = [0, 0, 0, 0, 0];
        devices.forEach(device => {
          if (device.typeId >= 1 && device.typeId <= 5) {
            deviceTypeCounts[device.typeId - 1]++;
          }
        });
        this.pieChartData.datasets[0].data = deviceTypeCounts;

        this.$nextTick(() => {
          this.$refs.barChart?.update && this.$refs.barChart.update();
          this.$refs.pieChart?.update && this.$refs.pieChart.update();
        });
      } catch (error) {
        console.error('数据加载失败:', error);
        Message.error('数据加载失败，请稍后再试');
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style scoped>
.data-visualization {
  padding: 30px;
  background: #f7f8fa;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin: 0;
}
.select-container {
  flex: 1;
  max-width: 600px;
}

.custom-select-container {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  transition: all 0.3s ease;
  overflow: hidden;
}
.custom-select-container:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}
.el-select .el-input__wrapper {
  border: none;
  background: #fff;
  height: 44px;
  line-height: 44px;
  padding: 0 16px;
  font-size: 14px;
  color: #666;
}
.custom-select-popup {
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.1);
  border: 1px solid #e5e7eb;
}
.custom-select-popup .el-select-dropdown__item {
  padding: 8px 16px;
  transition: background-color 0.2s ease;
}
.custom-select-popup .el-select-dropdown__item:hover {
  background: #f1f5ff;
}

.chart-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0,0,0,0.05);
  padding: 20px;
  margin-bottom: 20px;
}
.chart-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin-bottom: 15px;
}
.chart-wrapper {
  width: 100%;
  height: 100%;
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
  }
  .header h2 {
    margin-bottom: 10px;
  }
}
</style>